﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;

namespace JwtAuthSample.Common
{
    public class MyTokenValidate : ISecurityTokenValidator
    {
        public bool CanValidateToken => true;

        public int MaximumTokenSizeInBytes { get; set; }

        public bool CanReadToken(string securityToken)
        {
            return true;
        }


        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {

            validatedToken = null;

            //自定义算法生成token的逻辑(这里不做实现)
            if (securityToken != "abcdefg")
            {
                return null;
            }

            var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);

            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "1"));
            identity.AddClaim(new Claim("name", "zhangsan"));
            identity.AddClaim(new Claim(ClaimsIdentity.DefaultRoleClaimType, "admin"));
            identity.AddClaim(new Claim("Remark", "备注一下!"));
            identity.AddClaim(new Claim("SuperAdminOnly", "true"));

            //ClaimsPrincipal:就是用户的身份
            var princpal = new ClaimsPrincipal(identity);


            return princpal;

        }
    }
}
